package com.eqdd.yiqidian.ui.discover.workdiary;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.eqdd.yiqidian.ListItem132Custom;
import com.eqdd.yiqidian.ListItem94Custom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.WorkDiaryBean;
import com.eqdd.yiqidian.box.ItemDecoration.DashDividerLineItemDecoration;
import com.eqdd.yiqidian.box.ItemDecoration.SectionDividerItemDecoration;
import com.eqdd.yiqidian.box.span.NoLineClickSpan;
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource;
import com.eqdd.yiqidian.helper.mvchelper.Rx2DataSource;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.ui.InputDialogActivity;
import com.eqdd.yiqidian.ui.mine.UserCardActivity;
import com.eqdd.yiqidian.utils.ClickUtil;
import com.eqdd.yiqidian.utils.DensityUtil;
import com.eqdd.yiqidian.utils.HttpUtil;
import com.eqdd.yiqidian.utils.ImageUtil;
import com.eqdd.yiqidian.utils.TimeUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.FlowableBody;
import com.shizhefei.mvc.MVCCoolHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.Flowable;

public class WorkDiaryChildCommentActivity extends BaseActivity {
    private ListItem132Custom dataBinding;
    private boolean isMyComment;
    private int parentId;
    private String parentUserGuid;
    private int commentId;
    private String talkTo;
    private String talkContent;
    private int type;
    private MaterialDialog moreDialog;
    private int id;
    private int pageNum;
    private int firstCommentId;
    private SlimAdapterEx<WorkDiaryBean.CommentBean> slimAdapterEx;
    private MVCCoolHelper<List<WorkDiaryBean.CommentBean>> mvcHelper;
    private int dealPos;
    private boolean isCommentUp;
    WorkDiaryBean.CommentBean commentBean;
    private String mType; //0－日志，１－企业动态
    private View view;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.list_item_132);
        initTopTitleBar(View.VISIBLE, "所有评论");
        mType = getIntent().getStringExtra(Config.TYPE);
    }

    @Override
    public void initData() {
        commentBean = (WorkDiaryBean.CommentBean) getIntent().getSerializableExtra(Config.BEAN);
        id = getIntent().getIntExtra(Config.ID, 0);
        firstCommentId = commentBean.getId();
        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_138, new SlimInjector<WorkDiaryBean.CommentBean>() {
            @Override
            public void onInject(WorkDiaryBean.CommentBean data, IViewInjector injector) {
                injector.with(R.id.tv_comment_comment, view -> {
                    TextView textView = (TextView) view;
                    SpannableString spStr = new SpannableString(data.getCreateStaffName() + ":" + " @" + data.getParentStaffName() + " " + data.getContent());
                    NoLineClickSpan firstSpan = new NoLineClickSpan("#3423ff", v -> {

                        Bundle bundle = new Bundle();
                        bundle.putString(Config.GUID, data.getCreater());
                        startActivity(UserCardActivity.class, bundle);
                    });
                    NoLineClickSpan secondSpan = new NoLineClickSpan("#3423ff", v -> {
                        Bundle bundle = new Bundle();
                        bundle.putString(Config.GUID, data.getParentUserGuid());
                        startActivity(UserCardActivity.class, bundle);
                    });
                    spStr.setSpan(firstSpan, 0, data.getCreateStaffName().length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                    spStr.setSpan(secondSpan, spStr.toString().indexOf("@"), spStr.toString().indexOf("@") + 1 + data.getParentStaffName().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                    textView.setMovementMethod(LinkMovementMethod.getInstance());
                    textView.setText(spStr);
                });
            }
        }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());
        ItemClickSupport.addTo(dataBinding.recyclerView)
                .setOnItemClickListener((recyclerView1, position, v) -> {
                    WorkDiaryBean.CommentBean dataItem = slimAdapterEx.getDataItem(position);
                    isMyComment = dataItem.getCreater().equals(AppConstent.user.getGuid());
                    parentId = dataItem.getId();
                    parentUserGuid = dataItem.getCreater();
                    commentId = dataItem.getId();
                    talkTo = dataItem.getCreateStaffName();
                    talkContent = dataItem.getContent();
                    type = 2;
                    isCommentUp = false;
                    dealPos = position;
                    showMoreDialog();
                });

    }

    private void initView() {
        view = LayoutInflater.from(this).inflate(R.layout.list_item_137, null);
        ImageView ivCommentHead = view.findViewById(R.id.iv_comment_head);
        TextView tvCreater = view.findViewById(R.id.tv_creater);
        TextView tvCount = view.findViewById(R.id.tv_count);
        TextView tvDepart = view.findViewById(R.id.tv_depart);
        TextView tvTime = view.findViewById(R.id.tv_time);
        ImageView replyMsg = view.findViewById(R.id.iv_img);
        TextView tvComment = view.findViewById(R.id.tv_comment);

        ImageUtil.setCircleImage(commentBean.getCreatePhoto(), ivCommentHead);
        tvCreater.setText(commentBean.getCreateStaffName());
        tvDepart.setText(commentBean.getCreateDepartment() + "-" + commentBean.getCreatePost());
        tvTime.setText(TimeUtil.formatWebTime(commentBean.getCreateTime()));
        tvCount.setText(commentBean.getCommentCount() + "");
        tvComment.setText(commentBean.getContent());
        ClickUtil.click(replyMsg, () -> {
            parentId = commentBean.getId();
            talkTo = commentBean.getCreateName();
            parentUserGuid = commentBean.getCreater();
            firstCommentId = commentBean.getId();
            isCommentUp = true;
            talkTo();
        });
        ClickUtil.click(tvComment, () -> {
            isMyComment = commentBean.getCreater().equals(AppConstent.user.getGuid());
            parentId = commentBean.getId();
            parentUserGuid = commentBean.getCreater();
            firstCommentId = commentBean.getId();
            commentId = commentBean.getId();
            talkTo = commentBean.getCreateName();
            talkContent = commentBean.getContent();
            type = 1;
            isCommentUp = true;
            showMoreDialog();
        });
        ClickUtil.click(ivCommentHead, () -> {
            Bundle bundle = new Bundle();
            bundle.putString(Config.GUID, commentBean.getCreater());
            startActivity(UserCardActivity.class, bundle);
        });

    }

    @Override
    public void setView() {
        initView();
        HashMap<String, String> map = new HashMap<>();
        String url;
        if ("1".equals(mType)) { //企业动态
            url = HttpConfig.BASE_URL + HttpConfig.TASK_CHILD_COMMENT;
            map.put("taskId", id + "");
        } else if ("0".equals(mType)) {//日志
            url = HttpConfig.BASE_URL + HttpConfig.DIARY_CHILD_COMMENT;
            map.put("dailyId", id + "");
        } else {
            return;
        }

        ModelRx2DataSource<WorkDiaryBean.CommentBean> dataSource = new ModelRx2DataSource<>(new ModelRx2DataSource.OnLoadSource() {
            @Override
            public Flowable<List> loadSource(int page, Rx2DataSource.DoneActionRegister register) {
                pageNum = page == 1 ? 0 : pageNum;
                return OkGo.<HttpResult<List<WorkDiaryBean.CommentBean>>>post(url)
                        .params(map)
                        .params("page", pageNum)
                        .params("firstCommentId", firstCommentId)
                        .converter(new JsonConverter<HttpResult<List<WorkDiaryBean.CommentBean>>>() {
                            @Override
                            public void test() {
                                super.test();
                            }
                        }).adapt(new FlowableBody<>())
                        .flatMap(listResultBean -> {
                            pageNum = listResultBean.getPage();
                            if (listResultBean.getStatus() == 200) {
                                return Flowable.just(listResultBean.getItems() == null ? new ArrayList<WorkDiaryBean.CommentBean>() : listResultBean.getItems());
                            } else {
                                ToastUtil.showShort(listResultBean.getMsg());
                                return Flowable.just(new ArrayList<>());
                            }
                        });

            }
        });
        slimAdapterEx.addHeader(view);
        mvcHelper = new MVCCoolHelper<>(dataBinding.coolRefreshView);
        mvcHelper.setDataSource(dataSource);
        mvcHelper.setAdapter(slimAdapterEx);
        mvcHelper.refresh();
    }

    private void showMoreDialog() {
        if (moreDialog == null) {
            ArrayList<Object> objects = new ArrayList<>();
            objects.add("回复");
            objects.add("复制");
            objects.add("删除");
            SlimAdapterEx slimAdapterEx = SlimAdapterEx.create().registerDefault(R.layout.list_item_54, new SlimInjector() {
                @Override
                public void onInject(Object data, IViewInjector injector) {

                    injector.text(R.id.tv_content, (String) data);
                }
            }).updateData(objects);
            moreDialog = new MaterialDialog.Builder(this)
                    .adapter(slimAdapterEx, new LinearLayoutManager(this))
                    .build();
            moreDialog.getRecyclerView().addItemDecoration(new SectionDividerItemDecoration(this)
                    .setHeadHeight(0)
                    .setRightPadding(DensityUtil.percentW(40))
                    .setLeftPadding(DensityUtil.percentW(40))
                    .setLastBootomHeght(0));
            ItemClickSupport.addTo(moreDialog.getRecyclerView())
                    .setOnItemClickListener((recyclerView, position, v) -> {
                        switch (position) {
                            case 0:
                                talkTo();
                                break;
                            case 1:
                                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                                // 将文本内容放到系统剪贴板里。
                                if (cm != null) {
                                    cm.setPrimaryClip(ClipData.newPlainText("Lable", talkContent));
                                }
                                ToastUtil.showShort("已复制");
                                break;
                            case 2:
                                deleteWorkDiaryComment(commentId, type, () -> {
                                    if (isCommentUp) {
                                        finish();
                                    } else {
                                        this.slimAdapterEx.getData().remove(dealPos);
                                        this.slimAdapterEx.notifyItemRemoved(dealPos);
                                    }
                                });
                                break;
                        }
                        moreDialog.dismiss();
                    });
        }
        SlimAdapterEx slimAdapterExMore = (SlimAdapterEx) moreDialog.getRecyclerView().getAdapter();
        if (isMyComment && slimAdapterExMore.getData().size() == 2) {
            slimAdapterExMore.getData().add("删除");
            slimAdapterExMore.notifyItemInserted(2);
        } else if (!isMyComment && slimAdapterExMore.getData().size() == 3) {
            slimAdapterExMore.getData().remove(2);
            slimAdapterExMore.notifyItemRemoved(2);
        }
        moreDialog.show();

    }

    private void talkTo() {
        Bundle bundle = new Bundle();
        bundle.putString(Config.TALK_TO, talkTo);
        startActivityForResult(InputDialogActivity.class, bundle, Config.INPUT);
    }

    public void commentWorkDiary(int articleId, int parentId, String content, String parentUserGuid, int firstCommentId, HttpUtil.ResultObjectBack resultBack) {
        String url;
        HashMap<String, String> map = new HashMap<>();
        if ("0".equals(mType)) {
            url = HttpConfig.BASE_URL + HttpConfig.DIARY_ADD_COMMIT;
            map.put("dailyId", articleId + "");
        } else if ("1".equals(mType)) {
            url = HttpConfig.BASE_URL + HttpConfig.TASK_ADD_COMMENT;
            map.put("taskId", articleId + "");
        } else {
            return;
        }

        OkGo.<HttpResult<WorkDiaryBean.CommentBean>>post(url)
                .params("userGuid", AppConstent.user.getGuid())
                .params(map)
                .params("parentId", parentId)
                .params("message", content)
                .params("parentUserGuid", parentUserGuid)
                .params("firstCommentId", firstCommentId)
                .execute(new DialogCallBack<HttpResult<WorkDiaryBean.CommentBean>>(WorkDiaryChildCommentActivity.this) {
                    @Override
                    public void onSuccess(Response<HttpResult<WorkDiaryBean.CommentBean>> response) {
                        HttpResult<WorkDiaryBean.CommentBean> httpResult = response.body();
                        // ToastUtil.showShort(httpResult.getMsg());
                        if (httpResult.getStatus() == 200) {
                            resultBack.onResultBack(httpResult.getItems());
                        }
                    }
                });
    }

    public void deleteWorkDiaryComment(int commentId, int type, HttpUtil.ResultBack resultBack) {
        String url;
        if ("0".equals(mType)) {
            url = HttpConfig.BASE_URL + HttpConfig.DIARY_DELETE_COMMENT;
        } else if ("1".equals(mType)) {
            url = HttpConfig.BASE_URL + HttpConfig.TASK_DELETE_COMMENT;
        } else {
            return;
        }
        OkGo.<HttpResult>post(url)
                .params("userGuid", AppConstent.user.getGuid())
                .params("commentId", commentId)
                .params("type", type)
                .execute(new DialogCallBack<HttpResult>(WorkDiaryChildCommentActivity.this) {
                    @Override
                    public void onSuccess(Response<HttpResult> response) {
                        HttpResult httpResult = response.body();
                        ToastUtil.showShort(httpResult.getMsg());
                        if (httpResult.getStatus() == 200) {
                            resultBack.onResultBack();
                        }
                    }
                });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Config.INPUT && resultCode == Config.SUCCESS) {
            String content = data.getStringExtra(Config.CONTENT);
            commentWorkDiary(id, parentId, content, parentUserGuid, firstCommentId, (commentBean) -> {
                slimAdapterEx.getData().add(0, (WorkDiaryBean.CommentBean) commentBean);
                slimAdapterEx.notifyItemInserted(0);
                mvcHelper.refresh();
            });
        }
    }
}
